<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Utilityy
 *
 * @author francesco
 */
class Utility {

    
    // this method return 1 is the thate is before today, else return 0
    public static function isOldDate($data){
        
    }
    
    
    // method to upload image
    // separe le 2 cose e per disco metti la piva
    // data contains all event info or disco info
    // file names: _discoPiva or id_eventName
    // discoorno is 1 if the img is for the disco 0 if is for the event
    public static function uploadImage($data, $destDir, $discoOrNo, $exist)     {
        
        // size of the flyer
        $fwidth=500;
        $fheigth=600;
        // size of the club logo
        $cwidth=500;
        $cheight=600;
        // size of the thumbnail in percentage
        $twidth=0.4;
        $theight=0.4;

        // this part is used to get the image
        $upload = new Zend_File_Transfer_Adapter_Http();
        $upload->setDestination($destDir);
        // set the validators
        $upload->addValidator('Size', false, '524288000');
        $upload->addValidator('Extension', false, 'jpg,png,jpeg,gif');
        //echo $destDir;

        if (!$upload->isValid()) {
            $messages = "Validation failure";
        }
        if ($upload->receive()) {
            $messages = "The file has been uploaded!";
        } else {
            $messages = implode($upload->getMessages());
        }


        // this part is used to move the image to the right position dependin if is event or disco
        if ($discoOrNo==0)
           $fileName = $data['id'] . "_" . $data['titolo'];
        else if($discoOrNo==1) {
            $fileName = "_" . $data['piva'];
        }
        else {

        }
        
        $file_name = $upload->getFileName('image', false);
        $name = explode('.', $file_name);
        $name[0] = $fileName;
        $new_name = implode('.', $name);
        // new name is the new file name that i am using;

        $file_path = $upload->getFileName('image');
        //echo "path: " .$file_path;
        // i move the file in upload
        /*
        $tmp_path = $destDir . '/' . $new_name;
        $new_path = '/upload/' . $new_name;
        echo "newpath:   " . $new_path;
        echo "tmpath:   " . $tmp_path;
        rename($file_path, $tmp_path);
        $file_path = $new_path;
        */
        // udate to the new name
        $path = explode('/', $file_path);
        $path[count($path) - 1] = $new_name;
        $new_path = implode('/', $path);
        //$image_name=rename($file_path, $new_path);
        // echo $new_path ."  =====  ". $file_path;
        rename($file_path, $new_path);
        
        // creating and replacing with thumbnail
        // UPDATE: i need to remove the ../public/ from the path
        $tmp=substr($new_path,10);//,strlen($new_path));
        // echo "<br />tmp: " . $tmp;
        // echo "<br />new_path: " .$new_path . "<br />";
        
        // echo "<br />CWD: ". getcwd() . "<br />";
        
        if ($discoOrNo==0){ // event
            Utility::createthumb($tmp, $tmp ,$fwidth,$fheigth); // create the flyer thumb
            // create the thumbnail
            list($width, $height) = getimagesize($tmp);
            $thumbwidth = $width * $twidth;
            $thumbheight = $height * $theight;

            /*
             * cecco
             *
             */
            $file_name = explode('/', $new_path);
            $file_name = end($file_name);

            $thumbpath="upload/thumb/" . $file_name; // qua
            //var_dump($thumbpath);
            //echo "<br />tw: " . $thumbwidth . "<br />th. ".$thumbheight . "<br />";
            Utility::createthumb($tmp, $thumbpath ,$thumbwidth,$thumbheight);
        }
        else{ // club 
            Utility::createthumb($tmp, $tmp ,$cwidth,$cheigth); // create the club thumb
        }
        
        $file_name = explode('/', $new_path);
        //echo "FILE:  ";
        //print_r($file_name);
        //echo end($file_name);
        $file_name = end($file_name);
        //echo "<br />file_name: " .$file_name . "<br />";

        // i set the new path to view it because it needs the / at start
        $new_path="/" . $tmp;
        
        // prepare the data for the db
        if ($discoOrNo==0){
            $image = array(
                "name" => $file_name,
                "full_name" => $new_path,
                "thumb_path" => $thumbpath,
                "id_event" => $data['id'],
                "type_image" => 'disco'
            );
        //print_r($image);
        }
        else {
            $image = array(
                "file_name" => $file_name,
                "full_path" => $new_path,
                "piva" => $data['piva'],
            );
        }

        // save the data into the db
        $disco = new Application_Model_DbTable_Administrator();
        $disco->setImageData($image, $discoOrNo, $exist);
  
        
        return $messages;

    }

 // start thumbnail methods
    
       /**
        * Function ditchtn($arr,$thumbname)
        * filters out thumbnails
        * @param $arr
        * @param $thumbname
        * @return $tmparr2
        *
        */
    static function ditchtn($arr,$thumbname)
    {
	foreach ($arr as $item)
	{
		if (!preg_match("/^".$thumbname."/",$item)){$tmparr[]=$item;}
	}
	return $tmparr;
    }  

/*
	Function createthumb($name,$filename,$new_w,$new_h)
	creates a resized image
	variables:
	$name		Original filename
	$filename	Filename of the resized image
	$new_w		width of resized image
	$new_h		height of resized image
 *      $inputSize      1 if you wanna use the input size param
*/	
    static function createthumb($name,$filename,$new_w,$new_h, $inputSize)
    {
	$system=explode(".",$name);
	if (preg_match("/jpg|jpeg/",$system[1])){$src_img=imagecreatefromjpeg($name);}
        //echo $name;
        //var_dump($src_img);
	if (preg_match("/png/",$system[1])){$src_img=imagecreatefrompng($name);}
	$old_x=imageSX($src_img);
	$old_y=imageSY($src_img);
	if ($old_x > $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$old_y*($new_h/$old_x);
	}
	if ($old_x < $old_y) 
	{
		$thumb_w=$old_x*($new_w/$old_y);
		$thumb_h=$new_h;
	}
	if ($old_x == $old_y) 
	{
		$thumb_w=$new_w;
		$thumb_h=$new_h;
	}
        if ($inputSize==1){ // use input params
            $dst_img=ImageCreateTrueColor($new_w,$new_h);
            imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,$old_x,$old_y);
        }else{ // use calculated params
            $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); 
            imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
        }
            if (preg_match("/png/",$system[1]))
	{
		imagepng($dst_img,$filename); 
	} else {
		imagejpeg($dst_img,$filename); 
	}
	imagedestroy($dst_img); 
	imagedestroy($src_img); 
    }

/*
        Function directory($directory,$filters)
        reads the content of $directory, takes the files that apply to $filter 
		and returns an array of the filenames.
        You can specify which files to read, for example
        $files = directory(".","jpg,gif");
                gets all jpg and gif files in this directory.
        $files = directory(".","all");
                gets all files.
*/
    static function directory($dir,$filters)
    {
	$handle=opendir($dir);
	$files=array();
	if ($filters == "all"){while(($file = readdir($handle))!==false){$files[] = $file;}}
	if ($filters != "all")
	{
		$filters=explode(",",$filters);
		while (($file = readdir($handle))!==false)
		{
			for ($f=0;$f<sizeof($filters);$f++):
				$system=explode(".",$file);
				if ($system[1] == $filters[$f]){$files[] = $file;}
			endfor;
		}
	}
	closedir($handle);
	return $files;
    }

 // end thumbnail methods

    // this method return 1 if the piva exist in our db else it return 0
    // 1 if disco 0 if risto
    public static function isExistingPiva($piva, $discoRisto) {

        try {
            require_once "models/Db/Db_Db.php";

            $db = Db_Db::conn();
            $statement = "SELECT * FROM disco WHERE piva='$piva'";

            $data = $db->fetchAll($statement);
            $data = $data[0];

            // i close the connection
            $db->closeConnection();
        } catch (Zend_Db_Exception $e) {
            echo $e->getMessage();
        }

        //print_r($data);
        if (empty($data)) {
            return false;
        }

        return true;
    }

    public static function isValidPiva($piva) {
        if ($pi == '')
            return '';
        if (strlen($pi) != 11)
            return "La lunghezza della partita IVA non &egrave;\n"
            . "corretta: la partita IVA dovrebbe essere lunga\n"
            . "esattamente 11 caratteri.\n";
        if (!ereg("^[0-9]+$", $pi))
            return "La partita IVA contiene dei caratteri non ammessi:\n"
            . "la partita IVA dovrebbe contenere solo cifre.\n";
        $s = 0;
        for ($i = 0; $i <= 9; $i += 2)
            $s += ord($pi[$i]) - ord('0');
        for ($i = 1; $i <= 9; $i += 2) {
            $c = 2 * ( ord($pi[$i]) - ord('0') );
            if ($c > 9)
                $c = $c - 9;
            $s += $c;
        }
        if (( 10 - $s % 10 ) % 10 != ord($pi[10]) - ord('0'))
            return "La partita IVA non &egrave; valida:\n"
            . "il codice di controllo non corrisponde.";
        return '';
    }

    // method to upload image
    // separe le 2 cose e per disco metti la piva
    // data contains all event info or disco info
    // file names: _discoPiva or id_eventName
    // discoorno is 1 if the img is for the disco 0 if is for the event
    public static function uploadImageGallery($piva, $destDir, $alt, $title) {
        // PS SHIT CODE
        
        // this part is used to get the image
        $upload = new Zend_File_Transfer_Adapter_Http();
        // set the validators
        $upload->setDestination($destDir);
        
        //if ($upload->isValid()) {
            try {
                $upload->receive();
            }
            catch (Zend_File_Transfer_Exception $e)
            {
                throw new Exception('Bad image data: '.$e->getMessage());
            }

            
            // this part is used to move the image to the right position dependin if is event or disco
            $today = date("YmdGis");
            $fileName = $piva . "_" . $today;
 
            $file_name = $upload->getFileName('image', false);
            $file_name2= $upload->getFileName('image');
            // getting image size
            list($iwidth, $iheight, $itype, $iattr)=getimagesize($file_name2);
            //echo "width: " . $iwidth . "height: " . $iheight;


            $name = explode('.', $file_name);
            $name[0] = $fileName;
            $new_name = implode('.', $name);
            // new name is the new file name that i am using;

            $file_path = $upload->getFileName('image');

            // udate to the new name
            $path = explode('/', $file_path);
            $path[count($path) - 1] = $new_name;
            $new_path = implode('/', $path);
            //$image_name=rename($file_path, $new_path);
            //echo $new_path ."  =====  ". $file_path;
            $new_path=strtolower($new_path);
            rename($file_path, $new_path);

            // UPDATE: i need to remove the ../public/ from the path
            //$tmp=substr($new_path,10);//,strlen($new_path));
            $tmp=$new_path;
            
            $mfwidth=500;
            $mfheight=600;
            // set the image according the proportion
            // get the proportion
            $wh=$iwidth/$iheight;
            //echo "wh: ". $wh;
            // check what to do 
            if($iwidth <= $mfwidth && $iheight <= $mfheight){
                // the image is in the max size
                // do nothing
                //echo "nothing";
            }else if($iwidth <= $mfwidth && $iheight >= $mfheight){ // image is ouf of height
                $iheight=$mfheight;
                $iwidth=floor($iheight*$wh);
                //echo "caso1:" . $iwidth . " hh: " . $iheight;
                Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
            }else if($iwidth >= $mfwidth && $iheight <= $mfheight){ // image is out of width
                $iwidth=$mfwidth;
                $iheight=floor($iwidth/$wh);
                //echo "caso2." . $iwidth . " hh: " . $iheight;
                Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
            }else{ // image is out of height and width
                // for now i set it based on the height
                $iheight=$mfheight;
                $iwidth=floor($iheight*$wh);
                //echo " caso3: " .$iwidth . " hh: " . $iheight;
                Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
            }

            
             // setting thumb size
            if($wh > 1.15){ // voglio 145x130 MAX quindi tengo il wh prefissato 1.15 dal layout
                // rotate left 270°
                //$source = imagecreatefromjpeg($tmp);
                //$rotate = imagerotate($source, 270, 0);
                //imagejpeg($rotate,$tmp);

                // set the thumb width for the preview
                $thumbwidth = 145;
                // set the thumb height for the preview
                $thumbheight = floor(145/$wh);
            }else{
                    // set the thumb width for the preview
                    $thumbwidth = floor(130*$wh);
                    // set the thumb height for the preview
                    $thumbheight = 130;

            }


            //echo "h: " . $thumbheight . "w: ".$thumbwidth;
       
           
            $file_name = explode('/', $new_path);
            $file_name = end($file_name);

            $thumbpath="club_img/thumb/" . $file_name; // qua

            if($iwidth<145 && $iheight<130){ // if the image is too small i dont make the thumb smaller
                Utility::createthumb($tmp, $thumbpath ,$iwidth,$iheight,1);
                //echo "    SMALL     ";
            }
            else{ // else use the smaller size
                Utility::createthumb($tmp, $thumbpath ,$thumbwidth,$thumbheight,1);
                //echo "::::: BIG ::::";
            }
            
            $file_name = explode('/', $new_path);

            $file_name = end($file_name);

            // i set the new path to view it because it needs the / at start
            $new_path="/" . $tmp;

            // prepare the data for the db
            $image = array(
                    "img_path" => $new_path,
                    "img_thumb" => $thumbpath,
                    "piva" => $piva,
                    "alt" =>$alt,
                    "title"=>$title,
                );

            // save the data into the db
            require_once 'models/Db/Gallery_db.php';
            $club = new Gallery_db();

            $err = $club->setImageData($image);
            if ($err==true)
                $messages = "try again, there is an error!";
            else
                $messages = "yes";

  //      } else { //is not valid
  //          $messages = "Validation failure";
  //      }
      
        return $messages;
    }

    /**
     * this method is used to create the thumb for an event and save the relative data into a db
     *
     * @param <type> $data the data for the thumb name
     * @param <type> $file_name the full path of the image
     * @param <type> $destDir
     * @param <type> $createEvent if i have to create the event is ==1 else ==0
     */
    public static function makeThumbEvent($data, $file_name, $destDir,$createEvent) {
        // PS SHIT CODE
        
        
        // getting image size
        list($iwidth, $iheight, $itype, $iattr)=getimagesize($file_name);
        //echo "width: " . $iwidth . "height: " . $iheight;

        // the path of the file
        $file_path = $file_name;
        //echo  "file_path: " . $file_path;
        $fileName = $data['id'] ;//. "_" . $data['titolo'];
        //echo"fileName:" . $fileName;

        // changing the name
        $name = explode('/', $file_path);
        $name=$name[count($name)-1];
        //echo "name: ".$name;
        $name = explode('.', $name);
        $name[0] = $fileName;
        $new_name = implode('.', $name);
        // new name is the new file name that i am using;
        //echo "new name: " . $new_name;

        // udate to the new name
        $path = explode('/', $file_path);
        $path[count($path) - 1] = $new_name;
        $new_path = implode('/', $path);
        $new_path=strtolower($new_path);
        //echo "new_path " . $new_path . "file_path" . $file_path;

        //$image_name=rename($file_path, $new_path);
        //echo $new_path ."  =====  ". $file_path;
        rename($file_path, $new_path);
        //echo "FILE PATH". $file_path;
        // creating and replacing with thumbnail
        // UPDATE: i need to remove the ../public/ from the path
        //echo "NEW PATH" . $new_path;
        $tmp=$new_path;
        //$tmp=substr($new_path,10);
        //echo "<br />new_path: " .$new_path . "<br />";

        //echo "<br />CWD: ". getcwd() . "<br />";

        // setting the size of the flyer
        // max size of the flyer
        $mfwidth=480;
        $mfheight=520;
        // set the image according the proportion
        // get the proportion
        $wh=$iwidth/$iheight;
        //echo "wh: ". $wh;
        // check what to do 
        if($iwidth <= $mfwidth && $iheight <= $mfheight){
            // the image is in the max size
            // do nothing
            //echo "nothing";
        }else if($iwidth <= $mfwidth && $iheight >= $mfheight){ // image is ouf of height
            $iheight=$mfheight;
            $iwidth=floor($iheight*$wh);
            //echo "caso1:" . $iwidth . " hh: " . $iheight;
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
        }else if($iwidth >= $mfwidth && $iheight <= $mfheight){ // image is out of width
            $iwidth=$mfwidth;
            $iheight=floor($iwidth/$wh);
            //echo "caso2." . $iwidth . " hh: " . $iheight;
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
        }else{ // image is out of height and width
            // i check if wh > 0.92 and i set depending on proportions
            if ($wh>0.92){
                $iwidth=$mfwidth;
                $iheight=floor($mfwidth/$wh);
            }else{
                $iheight=$mfheight;
                $iwidth=floor($mfheight*$wh);
            }
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the flyer thumb
        }

        
        // setting thumb size
        if($wh > 1.15){ // voglio 145x130 MAX quindi tengo il wh prefissato 1.15 dal layout
            // rotate left 270°
            //$source = imagecreatefromjpeg($tmp);
            //$rotate = imagerotate($source, 270, 0);
            //imagejpeg($rotate,$tmp);

            // set the thumb width for the preview
            $thumbwidth = 145;
            // set the thumb height for the preview
            $thumbheight = floor(145/$wh);
        }else{
                // set the thumb width for the preview
                $thumbwidth = floor(130*$wh);
                // set the thumb height for the preview
                $thumbheight = 130;

        }


        //echo "h: " . $thumbheight . "w: ".$thumbwidth;
        
        $file_name = explode('/', $new_path);
        $file_name = end($file_name);

        $thumbpath="upload/thumb/" . $file_name; // qua
        //var_dump($thumbpath);
        //public static function makeThumbEvent($data, $file_name, $destDir,$createEvent) {

        //echo $tmp;
        //echo "<br />new_path: " .$new_path . "<br />";

        if($iwidth<145 && $iheight<130){ // if the image is too small i dont make the thumb smaller
            Utility::createthumb($tmp, $thumbpath ,$iwidth,$iheight,1);
            //echo "    SMALL     ";
        }
        else{ // else use the smaller size
            Utility::createthumb($tmp, $thumbpath ,$thumbwidth,$thumbheight,1);
            //echo "::::: BIG ::::";
        }

        $file_name = explode('/', $new_path);
        //echo "FILE:  ";
        //print_r($file_name);
        //echo end($file_name);
        $file_name = end($file_name);
        //echo "<br />file_name: " .$file_name . "<br />";

        // i set the new path to view it because it needs the / at start
        $new_path="/" . $tmp;
        //$thumbpath= "/" . $thumbpath;

        // prepare the data for the db

            $image = array(
                "name" => $file_name,
                "full_name" => $new_path,
                "thumb_path" => $thumbpath,
                "id_event" => $data['id'],
                "type_image" => 'disco'
            );

            //print_r($image);
        // save the data into the db
        $disco = new Application_Model_DbTable_Administrator();
        if($createEvent==1) // i i have to create the event
            $disco->setImageData($image, 0, 0);
        else{    // the event already exist
            $disco->setImageData($image, 0, 1);
        }
    }

    

    public static function makeThumbCLub($data, $file_name, $destDir,$createEvent) {

          // getting image size
        list($iwidth, $iheight, $itype, $iattr)=getimagesize($file_name);
      
        // the path of the file
        $file_path = $file_name;
        //echo  "file_path: " . $file_path;
        $fileName = "_" . $data['piva'];
        //echo"fileName:" . $fileName;

        // changing the name
        $name = explode('/', $file_path);
        $name=$name[count($name)-1];
        //echo "name: ".$name;
        $name = explode('.', $name);
        $name[0] = $fileName;
        $new_name = implode('.', $name);
        // new name is the new file name that i am using;
        //echo "new name: " . $new_name;

        // udate to the new name
        $path = explode('/', $file_path);
        $path[count($path) - 1] = $new_name;
        $new_path = implode('/', $path);
        $new_path=strtolower($new_path);

        //echo "new_path " . $new_path . "file_path" . $file_path;

        //$image_name=rename($file_path, $new_path);
        //echo $new_path ."  =====  ". $file_path;
        rename($file_path, $new_path);

        // creating and replacing with thumbnail
        // UPDATE: i need to remove the ../public/ from the path
        $tmp=$new_path;
        //$tmp=substr($new_path,10);
        //echo "<br />new_path: " .$new_path . "<br />";

        //echo "<br />CWD: ". getcwd() . "<br />";

        $mfwidth=470;
        $mfheight=370;
        // set the image according the proportion
        // get the proportion
        $wh=$iwidth/$iheight;
        //echo "wh: ". $wh;
        // check what to do 
        if($iwidth <= $mfwidth && $iheight <= $mfheight){
            // the image is in the max size
            // do nothing
            //echo "nothing";
        }else if($iwidth <= $mfwidth && $iheight >= $mfheight){ // image is ouf of height
            $iheight=$mfheight;
            $iwidth=floor($iheight*$wh);
            //echo "caso1:" . $iwidth . " hh: " . $iheight;
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the club image
        }else if($iwidth >= $mfwidth && $iheight <= $mfheight){ // image is out of width
            $iwidth=$mfwidth;
            $iheight=floor($iwidth/$wh);
            //echo "caso2." . $iwidth . " hh: " . $iheight;
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the club image
        }else{ // image is out of height and width
            // i check if wh > 0.92 and i set depending on proportions
            if ($wh>1.27){
                $iwidth=$mfwidth;
                $iheight=floor($mfwidth/$wh);
            }else{
                $iheight=$mfheight;
                $iwidth=floor($mfheight*$wh);
            }
            Utility::createthumb($tmp, $tmp ,$iwidth,$iheight,1); // create the club image
        }
        
        // thumb 200x180

        // setting thumb size
        if($wh > 1.11){ // voglio 145x130 MAX quindi tengo il wh prefissato 1.15 dal layout
            // set the thumb width for the preview
            $thumbwidth = 200;
            // set the thumb height for the preview
            $thumbheight = floor(200/$wh);
        }else{
                // set the thumb width for the preview
                $thumbwidth = floor(180*$wh);
                // set the thumb height for the preview
                $thumbheight = 180;

        }


        $file_name = explode('/', $new_path);
        $file_name = end($file_name);

        $thumbpath="club_img/thumb/" . $file_name; // qua
        //var_dump($thumbpath);
       
        if($iwidth<145 && $iheight<130){ // if the image is too small i dont make the thumb smaller
            Utility::createthumb($tmp, $thumbpath ,$iwidth,$iheight,1);
            //echo "    SMALL     ";
        }
        else{ // else use the smaller size
            Utility::createthumb($tmp, $thumbpath ,$thumbwidth,$thumbheight,1);
            //echo "::::: BIG ::::";
        }

        $file_name = explode('/', $new_path);
        //echo "FILE:  ";
        //print_r($file_name);
        //echo end($file_name);
        $file_name = end($file_name);
        //echo "<br />file_name: " .$file_name . "<br />";

        // i set the new path to view it because it needs the / at start
        $new_path="/" . $tmp;
        $thumbpath= "/". $thumbpath;
        //echo "path:" . $new_path;
        // prepare the data for the db

            $image = array(
                "file_name" => $file_name,
                "full_path" => $new_path,
                "thumb_path" => $thumbpath,
                "piva" => $data['piva'],
            );

        //print_r($image);
        // save the data into the db
        $disco = new Application_Model_DbTable_Administrator();
        if($createEvent==1) // i i have to create the event
            $disco->setImageData($image, 1, 0);
        else{    // the event already exist
            //$disco->setImageData($image, 1, 1);
        }

    }
    
    /**
     *
     * Questa funzione taglia il $text in ingresso al mnumero di caratteri $max_length
     * e inserisce alla fine $tail.
     * 
     * @param type $text
     * @param type $max_length
     * @param type $tail
     * @return string 
     */
    static function trim_body($text, $max_length = 500, $tail = '... <i>continua</i>') {
          $tail_len = strlen($tail);
          if (strlen($text) > $max_length) {
              $tmp_text = substr($text, 0, $max_length - $tail_len);
              if (substr($text, $max_length - $tail_len, 1) == ' ') {
                  $text = $tmp_text;
              }
              else {
                  $pos = strrpos($tmp_text, ' ');
                  $text = substr($text, 0, $pos);
		}
              $text = $text . $tail;
          }
          return $text;
      }


   static function createTweet($title, $description){
       $title = strtoupper(strip_tags($title));
       $html_descrizione = html_entity_decode($description);
       $description_new = Utility::trim_body(strip_tags($html_descrizione), 100);
       $tweet = $title . " - " . $description_new . " http://www.whichclub.it/Index/eventi";
       return $tweet;
   }


   /**
     * Questa funzione ritorna le piva
     * dei locali residenti in paese
     *
     * @param <string> $paese
     * @return <string> $piva
     */
    static public function getPivaDsicoByNameDisco($name){
    try{
        require_once "models/Db/Db_Db.php";

        $db=Db_Db::conn();
        $statement="SELECT piva FROM disco WHERE name='" .$name. "'";
        $pivaList=$db->fetchAll($statement);

        $db->closeConnection();

    } catch(Zend_Db_Exception $e) {
        echo $e->getMessage();
        }
        return $pivaList;//= array_unique($pivaList);
    }

    /**
     *
     * @param <type> $name
     * @return <type> 
     */
    static public function getPivaDiscoByNameUniqueDisco($name){
    try{
        require_once "models/Db/Db_Db.php";

        $db=Db_Db::conn();
        $statement="SELECT piva FROM disco WHERE unique_name='" .$name. "'";
        $pivaList=$db->fetchOne($statement);

        $db->closeConnection();

    } catch(Zend_Db_Exception $e) {
        echo $e->getMessage();
        }
        return $pivaList;//= array_unique($pivaList);
    }

    /**
     * get the unique name of a disco
     *
     * @param <type> $name
     * @return <type>
     */
    static public function getUniqueDiscoName($name){
        try{
            require_once "models/Db/Db_Db.php";

            $db=Db_Db::conn();
            $statement="SELECT name FROM disco WHERE unique_name='" .$name. "'";
            $name_disco=$db->fetchOne($statement);

            $db->closeConnection();

        } catch(Zend_Db_Exception $e) {
            echo $e->getMessage();
            }
            return $name_disco;//= array_unique($pivaList);
        }

    /**
     *
     * @param <type> $a
     * @param <type> $subkey
     * @return <type>
     */
    public static function subval_sort($a, $subkey){
        foreach($a as $k=>$v) {
        		$b[$k] = strtolower($v[$subkey]);
        	}
        	asort($b);
        	foreach($b as $key=>$val) {
        		$c[] = $a[$key];
        	}
        	return $c;
    }
}

?>
